package edu.stanford.prpl.impl.app;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import edu.stanford.prpl.api.BlobResource;
import edu.stanford.prpl.api.QueryResultIterator;
import edu.stanford.prpl.api.Resource;

public class AppClientQueryResult implements QueryResultIterator {

	private List<Map<String, ?>> result;
	private HashSet<String> allVars;
	private int currentRow = -1;

	public AppClientQueryResult(List<Map<String, ?>> result) {
		this.result = result;
		allVars = new LinkedHashSet<String>();
		for (Map<String, ?> hashtable : result) {
			allVars.addAll(hashtable.keySet());
		}
	}

	public List<String> getResultVars() {
		return new ArrayList<String>(allVars);
	}

	public int getRowNumber() {
		return currentRow;
	}

	public boolean hasNext() {
		return currentRow + 1 < result.size();
	}

	public boolean isOrdered() {
		return false;
	}

	public Solution next() {
		return new AppClientQuerySolution(result.get(++currentRow));
	}

	private class AppClientQuerySolution implements Solution {
		private Map<String, ?> solution;

		public AppClientQuerySolution(Map<String, ?> solution) {
			this.solution = solution;
		}

		public boolean contains(String varName) {
			return solution.containsKey(varName);
		}

		public Object get(String varName) {
			return solution.get(varName);
		}

		public BlobResource getBlobResource(String varName) {
			return (BlobResource) solution.get(varName);
		}

		public Resource getResource(String varName) {
			return (Resource) solution.get(varName);
		}

		public String getString(String varName) {
			Object o = solution.get(varName);
			return o == null ? null : o.toString();
		}

		public Iterator<String> varNames() {
			return solution.keySet().iterator();
		}
	}
}
